{#-*- coding: utf-8 -*-#}
{#@author: liuhuaijin#}
{#@email: liuhuaijin@shanshu.ai#}
{#@date: 2025/8/8 14:52#}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>航班信息生成器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 10px;
            background-color: #f5f5f5;
            font-size: 14px;
        }
        .container {
            max-width: 100%;
            margin: 0 auto;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-section {
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .form-group {
            margin-bottom: 10px;
            display: flex;
            flex-direction: column;
        }
        label {
            font-weight: bold;
            margin-bottom: 5px;
        }
        input, select, textarea {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 3px;
            width: 100%;
            box-sizing: border-box;
        }
        .segment-tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 10px;
            overflow-x: auto;
            white-space: nowrap;
        }
        .segment-tab {
            padding: 8px 12px;
            cursor: pointer;
            border: 1px solid #ddd;
            border-bottom: none;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
            background: #f0f0f0;
            min-width: 80px;
            text-align: center;
        }
        .segment-tab.active {
            background: #007bff;
            color: white;
        }
        .segment-content {
            display: none;
        }
        .segment-content.active {
            display: block;
        }
        .segment-item {
            border: 1px solid #eee;
            padding: 10px;
            margin: 5px 0;
            background: #f9f9f9;
        }
        .btn {
            padding: 10px 15px;
            margin: 5px 0;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            width: 100%;
            box-sizing: border-box;
        }
        .btn-primary {
            background: #007bff;
            color: white;
        }
        .btn-success {
            background: #28a745;
            color: white;
        }
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        .btn-warning {
            background: #ffc107;
            color: black;
        }
        .tab-container {
            margin-top: 15px;
        }
        .tab-buttons {
            display: flex;
            border-bottom: 1px solid #ddd;
            overflow-x: auto;
        }
        .tab-button {
            padding: 10px 15px;
            cursor: pointer;
            border: 1px solid transparent;
            border-bottom: none;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
            white-space: nowrap;
        }
        .tab-button.active {
            background: #007bff;
            color: white;
        }
        .tab-content {
            padding: 15px;
            border: 1px solid #ddd;
            border-top: none;
        }
        .tab-pane {
            display: none;
        }
        .tab-pane.active {
            display: block;
        }
        .upgrade-price-item {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            flex-wrap: wrap;
        }
        .upgrade-price-item input {
            margin-right: 5px;
            width: calc(50% - 40px);
        }
        .segment-actions {
            margin-top: 10px;
            display: flex;
            flex-direction: column;
        }
        .save-status {
            margin-top: 10px;
            font-size: 12px;
            color: #28a745;
            display: none;
            text-align: center;
        }
        .auto-save-notice {
            background: #e7f3ff;
            padding: 8px;
            border-radius: 4px;
            margin-bottom: 10px;
            font-size: 12px;
            color: #0066cc;
        }
        .print-notice {
            background: #fff3cd;
            padding: 8px;
            border-radius: 4px;
            margin-bottom: 10px;
            font-size: 12px;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        /* 头等舱布局样式 */
        .first-class-layout-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .first-class-layout-checkbox {
            width: auto;
            margin: 0;
        }
        .first-class-layout-label {
            font-weight: normal;
            margin: 0;
        }
        
        /* 桌面端样式 */
        @media (min-width: 768px) {
            body {
                margin: 20px;
                font-size: 16px;
            }
            .container {
                max-width: 1200px;
                padding: 20px;
            }
            .form-group {
                flex-direction: row;
                align-items: center;
            }
            label {
                width: 120px;
                margin-bottom: 0;
            }
            input, select, textarea {
                width: auto;
                flex: 1;
            }
            .btn {
                width: auto;
                margin: 5px;
            }
            .segment-actions {
                flex-direction: row;
            }
            .upgrade-price-item input {
                width: 80px;
            }
            .first-class-layout-group {
                margin-left: 120px; /* 与标签对齐 */
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🐡航班小条</h1>
        
        <div class="auto-save-notice">
            ⭐️：祝🐡🐡起落安妥，暴富暴富！！
        </div>
        
        <div class="print-notice">
            ❤️：本网页专属🐡使用，作者🥚，爱你❤️
        </div>
        
        <div class="tab-container">
            <div class="tab-buttons">
                <div class="tab-button active" onclick="switchTab('flight')">航班信息</div>
                <div class="tab-button" onclick="switchTab('basic')">基础数据维护</div>
            </div>
            
            <div class="tab-content">
                <!-- 航班信息标签页 -->
                <div id="flight-tab" class="tab-pane active">
                    <div class="form-section">
                        <h3>基本信息</h3>
                        <div class="form-group">
                            <label>日期:</label>
                            <input type="date" id="date" onchange="autoSave()">
                        </div>
                        <div class="form-group">
                            <label>星期:</label>
                            <select id="week" onchange="autoSave()">
                                <option value="">请选择</option>
                                <option value="星期一">星期一</option>
                                <option value="星期二">星期二</option>
                                <option value="星期三">星期三</option>
                                <option value="星期四">星期四</option>
                                <option value="星期五">星期五</option>
                                <option value="星期六">星期六</option>
                                <option value="星期日">星期日</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>航线名称:</label>
                            <input type="text" id="route_name" onchange="autoSave()">
                        </div>
                        <div class="form-group">
                            <label>航班号:</label>
                            <input type="text" id="flight_number" onchange="autoSave()">
                        </div>
                        <div class="form-group">
                            <label>飞机号:</label>
                            <input type="text" id="plane_number" onchange="autoSave()">
                        </div>
                        <div class="form-group">
                            <label>机长及配置:</label>
                            <input type="text" id="captain_config" onchange="autoSave()">
                        </div>
                    </div>

                    <div class="form-section">
                        <h3>航段信息</h3>
                        <div class="segment-tabs" id="segment-tabs">
                            <!-- 航段标签将通过JavaScript动态添加 -->
                        </div>
                        <div id="segments-container">
                            <!-- 航段内容将通过JavaScript动态添加 -->
                        </div>
                        <div class="segment-actions">
                            <button class="btn btn-primary" onclick="addSegment()">添加航段</button>
                            <button class="btn btn-danger" onclick="removeCurrentSegment()">删除当前航段</button>
                        </div>
                    </div>

                    <div class="form-section">
                        <button class="btn btn-success" onclick="saveData()">手动保存</button>
                        <button class="btn btn-primary" onclick="generateHTML()">生成HTML</button>
                        <button class="btn btn-danger" onclick="clearData()">清空数据</button>
                        <span class="save-status" id="saveStatus">已保存</span>
                    </div>
                </div>

                <!-- 基础数据维护标签页 -->
                <div id="basic-tab" class="tab-pane">
                    <div class="form-section">
                        <h3>机场维护</h3>
                        <div id="airports-container">
                            <!-- 机场列表将通过JavaScript动态添加 -->
                        </div>
                        <button class="btn btn-primary" onclick="addAirport()">添加机场</button>
                    </div>

                    <div class="form-section">
                        <h3>餐食维护</h3>
                        <div id="meals-container">
                            <!-- 餐食列表将通过JavaScript动态添加 -->
                        </div>
                        <button class="btn btn-primary" onclick="addMeal()">添加餐食</button>
                    </div>

                    <div class="form-section">
                        <h3>升舱价格模板</h3>
                        <div id="templates-container">
                            <!-- 模板列表将通过JavaScript动态添加 -->
                        </div>
                        <button class="btn btn-primary" onclick="addTemplate()">添加模板</button>
                    </div>

                    <button class="btn btn-success" onclick="saveBasicData()">保存基础数据</button>
                    <span class="save-status" id="basicSaveStatus">已保存</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentData = {};
        let basicData = {};
        let currentSegmentIndex = 0;
        let autoSaveTimer = null;

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadData();
            // 为所有输入元素添加自动保存监听
            setTimeout(() => {
                addAutoSaveListeners();
            }, 1000);
        });

        // 添加自动保存监听器
        function addAutoSaveListeners() {
            // 为所有输入框、选择框、文本域添加change事件
            document.querySelectorAll('input, select, textarea').forEach(element => {
                if (!element.onchange) {
                    element.addEventListener('change', autoSave);
                }
                if (element.type === 'text' || element.type === 'textarea') {
                    element.addEventListener('input', function() {
                        clearTimeout(autoSaveTimer);
                        autoSaveTimer = setTimeout(autoSave, 1000);
                    });
                }
            });
        }

        // 自动保存
        async function autoSave() {
            const success = await saveData(false); // 不显示提示
            if (success) {
                showSaveStatus('saveStatus');
            }
        }

        // 显示保存状态
        function showSaveStatus(elementId) {
            const statusElement = document.getElementById(elementId);
            if (statusElement) {
                statusElement.style.display = 'inline';
                statusElement.textContent = '已保存';
                setTimeout(() => {
                    statusElement.style.display = 'none';
                }, 2000);
            }
        }

        // 切换标签页
        function switchTab(tabName) {
            document.querySelectorAll('.tab-button').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelectorAll('.tab-pane').forEach(pane => {
                pane.classList.remove('active');
            });
            
            event.target.classList.add('active');
            document.getElementById(tabName + '-tab').classList.add('active');
            
            // 切换到新标签页后重新添加监听器
            setTimeout(addAutoSaveListeners, 100);
        }

        // 加载数据
        async function loadData() {
            try {
                const response = await fetch('/api/data');
                const data = await response.json();
                currentData = data.current_data;
                basicData = data.basic_data;
                
                populateForm();
                populateBasicDataForms();
            } catch (error) {
                console.error('加载数据失败:', error);
            }
        }

        // 填充表单
        function populateForm() {
            // 基本信息
            document.getElementById('date').value = currentData.date || '';
            document.getElementById('week').value = currentData.week || '';
            document.getElementById('route_name').value = currentData.route_name || '';
            document.getElementById('flight_number').value = currentData.flight_number || '';
            document.getElementById('plane_number').value = currentData.plane_number || '';
            document.getElementById('captain_config').value = currentData.captain_config || '';
            
            // 航段信息
            renderSegmentTabs();
            renderSegmentContent();
            
            // 默认显示第一个航段
            if (currentData.segments && currentData.segments.length > 0) {
                switchToSegment(0);
            }
        }

        // 渲染航段标签
        function renderSegmentTabs() {
            const tabsContainer = document.getElementById('segment-tabs');
            tabsContainer.innerHTML = '';
            
            if (currentData.segments && currentData.segments.length > 0) {
                currentData.segments.forEach((segment, index) => {
                    const tab = document.createElement('div');
                    tab.className = `segment-tab ${index === currentSegmentIndex ? 'active' : ''}`;
                    tab.textContent = `航段 ${segment.segment_number || index + 1}`;
                    tab.onclick = () => switchToSegment(index);
                    tabsContainer.appendChild(tab);
                });
            }
        }

        // 渲染航段内容
        function renderSegmentContent() {
            const container = document.getElementById('segments-container');
            container.innerHTML = '';
            
            if (currentData.segments && currentData.segments.length > 0) {
                currentData.segments.forEach((segment, index) => {
                    const content = document.createElement('div');
                    content.className = `segment-content ${index === currentSegmentIndex ? 'active' : ''}`;
                    content.id = `segment-content-${index}`;
                    content.innerHTML = createSegmentForm(segment, index);
                    container.appendChild(content);
                });
            }
            
            // 重新添加自动保存监听器
            setTimeout(addAutoSaveListeners, 100);
        }

        // 创建航段表单
        function createSegmentForm(segment, index) {
            // 确保first_class_layout是布尔值
            const firstClassLayout = segment.first_class_layout === true || segment.first_class_layout === 'true';
            
            return `
                <div class="form-section">
                    <h4>航段 ${segment.segment_number || index + 1} 基本信息</h4>
                    <div class="form-group">
                        <label>段数:</label>
                        <input type="text" value="${segment.segment_number || index + 1}" placeholder="如：1" onchange="updateSegmentData(${index}, 'segment_number', this.value); updateSegmentTab(${index}); autoSave();">
                    </div>
                    <div class="form-group">
                        <label>起飞时间:</label>
                        <input type="time" value="${segment.departure_time || ''}" onchange="updateSegmentData(${index}, 'departure_time', this.value); autoSave();">
                    </div>
                    <div class="form-group">
                        <label>降落时间:</label>
                        <input type="time" value="${segment.arrival_time || ''}" onchange="updateSegmentData(${index}, 'arrival_time', this.value); autoSave();">
                    </div>
                    <div class="form-group">
                        <label>飞行时长:</label>
                        <input type="text" value="${segment.duration || ''}" placeholder="如：2小时30分" onchange="updateSegmentData(${index}, 'duration', this.value); autoSave();">
                    </div>
                    <div class="form-group">
                        <label>飞行距离:</label>
                        <input type="text" value="${segment.distance || ''}" placeholder="如：1200公里" onchange="updateSegmentData(${index}, 'distance', this.value); autoSave();">
                    </div>
                    <div class="form-group">
                        <label>巡航高度:</label>
                        <input type="text" value="${segment.altitude || ''}" placeholder="如：10000米" onchange="updateSegmentData(${index}, 'altitude', this.value); autoSave();">
                    </div>
                    <div class="form-group">
                        <label>降落机场:</label>
                        <select class="airport-select" onchange="updateSegmentData(${index}, 'airport', this.value); autoSave();">
                            <option value="">请选择</option>
                            ${basicData.airports ? basicData.airports.map(airport => 
                                `<option value="${airport}" ${airport === segment.airport ? 'selected' : ''}>${airport}</option>`
                            ).join('') : ''}
                        </select>
                    </div>
                </div>

                <div class="form-section">
                    <h4>餐食信息</h4>
                    <div class="form-group">
                        <label>头等舱餐食:</label>
                        <select class="meal-select" onchange="updateSegmentData(${index}, 'first_class_meals', this.value); autoSave();">
                            <option value="">请选择</option>
                            ${basicData.meals ? basicData.meals.map(meal => 
                                `<option value="${meal}" ${meal === segment.first_class_meals ? 'selected' : ''}>${meal}</option>`
                            ).join('') : ''}
                        </select>
                    </div>
                    <div class="form-group">
                        <label>经济舱餐食:</label>
                        <select class="meal-select" onchange="updateSegmentData(${index}, 'economy_meals', this.value); autoSave();">
                            <option value="">请选择</option>
                            ${basicData.meals ? basicData.meals.map(meal => 
                                `<option value="${meal}" ${meal === segment.economy_meals ? 'selected' : ''}>${meal}</option>`
                            ).join('') : ''}
                        </select>
                    </div>
                    <div class="form-group">
                        <label>机组餐食:</label>
                        <select class="meal-select" onchange="updateSegmentData(${index}, 'crew_meals', this.value); autoSave();">
                            <option value="">请选择</option>
                            ${basicData.meals ? basicData.meals.map(meal => 
                                `<option value="${meal}" ${meal === segment.crew_meals ? 'selected' : ''}>${meal}</option>`
                            ).join('') : ''}
                        </select>
                    </div>
                </div>

                <div class="form-section">
                    <h4>升舱价格</h4>
                    <div class="form-group">
                        <label>选择模板:</label>
                        <select onchange="loadUpgradeTemplate(${index}, this.value); autoSave();">
                            <option value="">自定义</option>
                            ${basicData.upgrade_templates ? Object.keys(basicData.upgrade_templates).map(templateName => 
                                `<option value="${templateName}">${templateName}</option>`
                            ).join('') : ''}
                        </select>
                    </div>
                    <div id="upgrade-prices-container-${index}">
                        ${(segment.upgrade_prices || []).map(price => `
                            <div class="upgrade-price-item">
                                <input type="text" placeholder="舱位" value="${price.class}" onchange="updateUpgradePrice(${index}, this); autoSave();">
                                <input type="text" placeholder="价格" value="${price.price}" onchange="updateUpgradePrice(${index}, this); autoSave();">
                                <button class="btn btn-danger" onclick="removeUpgradePrice(this)">删除</button>
                            </div>
                        `).join('')}
                    </div>
                    <button class="btn btn-primary" onclick="addUpgradePrice(${index})">添加价格</button>
                </div>

                <div class="form-section">
                    <h4>其他信息</h4>
                    <div class="form-group">
                        <label>头等舱布局:</label>
                        <div class="first-class-layout-group">
                            <input type="checkbox" class="first-class-layout-checkbox" ${firstClassLayout ? 'checked' : ''} onchange="updateSegmentData(${index}, 'first_class_layout', this.checked); autoSave();">
                            <span class="first-class-layout-label">显示头等舱座位布局</span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>头等舱人数:</label>
                        <input type="text" class="first-class-count" value="${segment.first_class_count || ''}" onchange="updateSegmentData(${index}, 'first_class_count', this.value); autoSave();">
                    </div>
                    <div class="form-group">
                        <label>经济舱人数:</label>
                        <input type="text" class="economy-count" value="${segment.economy_count || ''}" onchange="updateSegmentData(${index}, 'economy_count', this.value); autoSave();">
                    </div>
                    <div class="form-group">
                        <label>特殊旅客清单:</label>
                        <textarea class="special-passengers" rows="3" onchange="updateSegmentData(${index}, 'special_passengers', this.value); autoSave();">${segment.special_passengers || ''}</textarea>
                    </div>
                </div>
            `;
        }

        // 更新航段数据 - 新增函数：实时更新内存中的数据
        function updateSegmentData(segmentIndex, field, value) {
            if (!currentData.segments) return;
            if (!currentData.segments[segmentIndex]) return;
            
            currentData.segments[segmentIndex][field] = value;
        }

        // 更新升舱价格数据
        function updateUpgradePrice(segmentIndex, inputElement) {
            if (!currentData.segments || !currentData.segments[segmentIndex]) return;
            
            const item = inputElement.closest('.upgrade-price-item');
            const inputs = item.querySelectorAll('input');
            const classValue = inputs[0].value;
            const priceValue = inputs[1].value;
            
            // 找到对应的价格项
            if (!currentData.segments[segmentIndex].upgrade_prices) {
                currentData.segments[segmentIndex].upgrade_prices = [];
            }
            
            // 查找是否已存在相同舱位的价格
            let found = false;
            currentData.segments[segmentIndex].upgrade_prices.forEach(price => {
                if (price.class === classValue) {
                    price.price = priceValue;
                    found = true;
                }
            });
            
            // 如果没找到，添加新项
            if (!found && classValue && priceValue) {
                currentData.segments[segmentIndex].upgrade_prices.push({
                    class: classValue,
                    price: priceValue
                });
            }
        }

        // 切换到指定航段
        function switchToSegment(index) {
            currentSegmentIndex = index;
            renderSegmentTabs();
            
            document.querySelectorAll('.segment-content').forEach(content => {
                content.classList.remove('active');
            });
            const currentContent = document.getElementById(`segment-content-${index}`);
            if (currentContent) {
                currentContent.classList.add('active');
            }
        }

        // 更新航段标签
        function updateSegmentTab(index) {
            const segmentContent = document.getElementById(`segment-content-${index}`);
            if (segmentContent) {
                const segmentNumberInput = segmentContent.querySelector('input[type="text"]');
                const tabs = document.querySelectorAll('.segment-tab');
                if (tabs[index] && segmentNumberInput) {
                    tabs[index].textContent = `航段 ${segmentNumberInput.value}`;
                }
            }
        }

        // 添加航段 - 修复：先保存当前数据再添加新航段
        function addSegment() {
            // 先保存当前所有航段的数据
            collectCurrentSegmentData();
            
            if (!currentData.segments) {
                currentData.segments = [];
            }
            
            const newSegment = {
                segment_number: (currentData.segments.length + 1).toString(),
                departure_time: "",
                arrival_time: "",
                duration: "",
                distance: "",
                altitude: "",
                airport: "",
                first_class_meals: "",
                economy_meals: "",
                crew_meals: "",
                upgrade_prices: [
                    {"class": "C", "price": "500"},
                    {"class": "Y", "price": "300"}
                ],
                first_class_layout: false,
                first_class_count: "",
                economy_count: "",
                special_passengers: ""
            };
            
            currentData.segments.push(newSegment);
            renderSegmentTabs();
            renderSegmentContent();
            switchToSegment(currentData.segments.length - 1);
            
            // 自动保存
            setTimeout(autoSave, 100);
        }

        // 收集当前所有航段的数据 - 新增函数
        function collectCurrentSegmentData() {
            if (!currentData.segments) return;
            
            document.querySelectorAll('.segment-content').forEach((content, index) => {
                if (index < currentData.segments.length) {
                    // 基本信息
                    currentData.segments[index].segment_number = content.querySelector('input[type="text"]')?.value || '';
                    currentData.segments[index].departure_time = content.querySelectorAll('input[type="time"]')[0]?.value || '';
                    currentData.segments[index].arrival_time = content.querySelectorAll('input[type="time"]')[1]?.value || '';
                    currentData.segments[index].duration = content.querySelectorAll('input[type="text"]')[1]?.value || '';
                    currentData.segments[index].distance = content.querySelectorAll('input[type="text"]')[2]?.value || '';
                    currentData.segments[index].altitude = content.querySelectorAll('input[type="text"]')[3]?.value || '';
                    currentData.segments[index].airport = content.querySelector('.airport-select')?.value || '';
                    
                    // 餐食信息
                    currentData.segments[index].first_class_meals = content.querySelectorAll('.meal-select')[0]?.value || '';
                    currentData.segments[index].economy_meals = content.querySelectorAll('.meal-select')[1]?.value || '';
                    currentData.segments[index].crew_meals = content.querySelectorAll('.meal-select')[2]?.value || '';
                    
                    // 其他信息
                    currentData.segments[index].first_class_layout = content.querySelector('.first-class-layout-checkbox')?.checked || false;
                    currentData.segments[index].first_class_count = content.querySelector('.first-class-count')?.value || '';
                    currentData.segments[index].economy_count = content.querySelector('.economy-count')?.value || '';
                    currentData.segments[index].special_passengers = content.querySelector('.special-passengers')?.value || '';
                    
                    // 升舱价格
                    const upgradeContainer = document.getElementById(`upgrade-prices-container-${index}`);
                    if (upgradeContainer) {
                        currentData.segments[index].upgrade_prices = [];
                        upgradeContainer.querySelectorAll('.upgrade-price-item').forEach(item => {
                            const priceInputs = item.querySelectorAll('input');
                            if (priceInputs[0].value && priceInputs[1].value) {
                                currentData.segments[index].upgrade_prices.push({
                                    class: priceInputs[0].value,
                                    price: priceInputs[1].value
                                });
                            }
                        });
                    }
                }
            });
        }

        // 删除当前航段
        function removeCurrentSegment() {
            // 先保存当前数据
            collectCurrentSegmentData();
            
            if (currentData.segments && currentData.segments.length > 1) {
                currentData.segments.splice(currentSegmentIndex, 1);
                if (currentSegmentIndex >= currentData.segments.length) {
                    currentSegmentIndex = currentData.segments.length - 1;
                }
                renderSegmentTabs();
                renderSegmentContent();
                if (currentData.segments.length > 0) {
                    switchToSegment(currentSegmentIndex);
                }
                
                // 自动保存
                setTimeout(autoSave, 100);
            } else {
                alert('至少需要保留一个航段！');
            }
        }

        // 添加升舱价格
        function addUpgradePrice(segmentIndex, classValue = '', priceValue = '') {
            const container = document.getElementById(`upgrade-prices-container-${segmentIndex}`);
            if (container) {
                const itemHtml = `
                    <div class="upgrade-price-item">
                        <input type="text" placeholder="舱位" value="${classValue}" onchange="updateUpgradePrice(${segmentIndex}, this); autoSave();">
                        <input type="text" placeholder="价格" value="${priceValue}" onchange="updateUpgradePrice(${segmentIndex}, this); autoSave();">
                        <button class="btn btn-danger" onclick="removeUpgradePrice(this)">删除</button>
                    </div>
                `;
                container.insertAdjacentHTML('beforeend', itemHtml);
                
                // 更新内存中的数据
                if (classValue && priceValue) {
                    if (!currentData.segments[segmentIndex].upgrade_prices) {
                        currentData.segments[segmentIndex].upgrade_prices = [];
                    }
                    currentData.segments[segmentIndex].upgrade_prices.push({
                        class: classValue,
                        price: priceValue
                    });
                }
            }
        }

        // 删除升舱价格
        function removeUpgradePrice(button) {
            const item = button.parentElement;
            const inputs = item.querySelectorAll('input');
            const classValue = inputs[0].value;
            
            // 从内存数据中删除
            const segmentContent = item.closest('.segment-content');
            if (segmentContent) {
                const segmentId = segmentContent.id.split('-')[2];
                const segmentIndex = parseInt(segmentId);
                
                if (currentData.segments && currentData.segments[segmentIndex] && currentData.segments[segmentIndex].upgrade_prices) {
                    currentData.segments[segmentIndex].upgrade_prices = currentData.segments[segmentIndex].upgrade_prices.filter(
                        price => price.class !== classValue
                    );
                }
            }
            
            item.remove();
            autoSave();
        }

        // 加载升舱模板
        function loadUpgradeTemplate(segmentIndex, templateName) {
            if (templateName && basicData.upgrade_templates && basicData.upgrade_templates[templateName]) {
                const container = document.getElementById(`upgrade-prices-container-${segmentIndex}`);
                if (container) {
                    container.innerHTML = '';
                    
                    // 更新内存中的数据
                    currentData.segments[segmentIndex].upgrade_prices = [];
                    
                    basicData.upgrade_templates[templateName].forEach(price => {
                        addUpgradePrice(segmentIndex, price.class, price.price);
                    });
                    
                    autoSave();
                }
            }
        }

        // 保存数据 - 修复数据收集逻辑
        async function saveData(showAlert = true) {
            try {
                // 先收集当前显示的所有航段数据
                collectCurrentSegmentData();
                
                // 收集基本信息
                const formData = {
                    date: document.getElementById('date').value,
                    week: document.getElementById('week').value,
                    route_name: document.getElementById('route_name').value,
                    flight_number: document.getElementById('flight_number').value,
                    plane_number: document.getElementById('plane_number').value,
                    captain_config: document.getElementById('captain_config').value,
                    segments: currentData.segments || []
                };
                
                const response = await fetch('/api/save', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(formData)
                });
                
                if (response.ok) {
                    if (showAlert) {
                        alert('保存成功！');
                    }
                    return true;
                } else {
                    if (showAlert) {
                        alert('保存失败！');
                    }
                    return false;
                }
            } catch (error) {
                console.error('保存失败:', error);
                if (showAlert) {
                    alert('保存失败！');
                }
                return false;
            }
        }

        // 生成HTML
        async function generateHTML() {
            const saved = await saveData(false); // 不显示提示
            if (!saved) {
                alert('保存失败，无法生成HTML！');
                return;
            }
            
            try {
                const response = await fetch('/api/generate', {
                    method: 'POST'
                });
                const result = await response.json();
                
                if (response.ok) {
                    // 在新窗口中打开HTML
                    window.open(`/static/${result.filename}`, '_blank');
                    alert('HTML生成成功！已在新窗口打开');
                } else {
                    alert('生成失败！');
                }
            } catch (error) {
                console.error('生成失败:', error);
                alert('生成失败！');
            }
        }

        // 清空数据
        async function clearData() {
            if (confirm('确定要清空所有数据吗？')) {
                try {
                    const response = await fetch('/api/clear', {
                        method: 'POST'
                    });
                    
                    if (response.ok) {
                        loadData();
                        alert('数据已清空！');
                    } else {
                        alert('清空失败！');
                    }
                } catch (error) {
                    console.error('清空失败:', error);
                    alert('清空失败！');
                }
            }
        }

        // 基础数据维护相关函数
        function populateBasicDataForms() {
            // 机场
            const airportsContainer = document.getElementById('airports-container');
            airportsContainer.innerHTML = '';
            if (basicData.airports) {
                basicData.airports.forEach(airport => {
                    addAirport(airport);
                });
            }
            
            // 餐食
            const mealsContainer = document.getElementById('meals-container');
            mealsContainer.innerHTML = '';
            if (basicData.meals) {
                basicData.meals.forEach(meal => {
                    addMeal(meal);
                });
            }
            
            // 模板
            const templatesContainer = document.getElementById('templates-container');
            templatesContainer.innerHTML = '';
            if (basicData.upgrade_templates) {
                Object.keys(basicData.upgrade_templates).forEach(templateName => {
                    addTemplate(templateName, basicData.upgrade_templates[templateName]);
                });
            }
        }

        function addAirport(value = '') {
            const container = document.getElementById('airports-container');
            const itemHtml = `
                <div class="form-group">
                    <input type="text" value="${value}" placeholder="机场名称" onchange="autoSaveBasicData();">
                    <button class="btn btn-danger" onclick="this.parentElement.remove(); autoSaveBasicData();">删除</button>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', itemHtml);
        }

        function addMeal(value = '') {
            const container = document.getElementById('meals-container');
            const itemHtml = `
                <div class="form-group">
                    <input type="text" value="${value}" placeholder="餐食名称" onchange="autoSaveBasicData();">
                    <button class="btn btn-danger" onclick="this.parentElement.remove(); autoSaveBasicData();">删除</button>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', itemHtml);
        }

        function addTemplate(name = '', prices = []) {
            const container = document.getElementById('templates-container');
            const templateId = 'template_' + Date.now();
            
            let pricesHtml = '';
            if (prices.length > 0) {
                prices.forEach((price, index) => {
                    pricesHtml += `
                        <div class="upgrade-price-item">
                            <input type="text" value="${price.class}" placeholder="舱位" onchange="autoSaveBasicData();">
                            <input type="text" value="${price.price}" placeholder="价格" onchange="autoSaveBasicData();">
                            ${index === 0 ? '<button class="btn btn-primary" onclick="addTemplatePrice(this)">添加</button>' : '<button class="btn btn-danger" onclick="removeTemplatePrice(this)">删除</button>'}
                        </div>
                    `;
                });
            } else {
                pricesHtml = `
                    <div class="upgrade-price-item">
                        <input type="text" placeholder="舱位" onchange="autoSaveBasicData();">
                        <input type="text" placeholder="价格" onchange="autoSaveBasicData();">
                        <button class="btn btn-primary" onclick="addTemplatePrice(this)">添加</button>
                    </div>
                `;
            }
            
            const itemHtml = `
                <div class="form-section" id="${templateId}">
                    <div class="form-group">
                        <label>模板名称:</label>
                        <input type="text" value="${name}" placeholder="模板名称" onchange="autoSaveBasicData();">
                    </div>
                    <div class="form-group">
                        <label>价格设置:</label>
                        <div>${pricesHtml}</div>
                    </div>
                    <button class="btn btn-danger" onclick="document.getElementById('${templateId}').remove(); autoSaveBasicData();">删除模板</button>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', itemHtml);
        }

        function addTemplatePrice(button) {
            const container = button.parentElement.parentElement;
            const newItemHtml = `
                <div class="upgrade-price-item">
                    <input type="text" placeholder="舱位" onchange="autoSaveBasicData();">
                    <input type="text" placeholder="价格" onchange="autoSaveBasicData();">
                    <button class="btn btn-danger" onclick="removeTemplatePrice(this)">删除</button>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', newItemHtml);
            autoSaveBasicData();
        }

        function removeTemplatePrice(button) {
            button.parentElement.remove();
            autoSaveBasicData();
        }

        // 基础数据自动保存
        async function autoSaveBasicData() {
            const success = await saveBasicData(false);
            if (success) {
                showSaveStatus('basicSaveStatus');
            }
        }

        async function saveBasicData(showAlert = true) {
            try {
                // 收集机场数据
                const airports = [];
                document.querySelectorAll('#airports-container input[type="text"]').forEach(input => {
                    if (input.value.trim()) {
                        airports.push(input.value.trim());
                    }
                });
                
                // 收集餐食数据
                const meals = [];
                document.querySelectorAll('#meals-container input[type="text"]').forEach(input => {
                    if (input.value.trim()) {
                        meals.push(input.value.trim());
                    }
                });
                
                // 收集模板数据
                const upgrade_templates = {};
                document.querySelectorAll('#templates-container > .form-section').forEach(section => {
                    const nameInput = section.querySelector('input[placeholder="模板名称"]');
                    const priceItems = section.querySelectorAll('.upgrade-price-item');
                    
                    if (nameInput && nameInput.value.trim()) {
                        const prices = [];
                        priceItems.forEach(item => {
                            const inputs = item.querySelectorAll('input');
                            if (inputs[0].value.trim() && inputs[1].value.trim()) {
                                prices.push({
                                    class: inputs[0].value.trim(),
                                    price: inputs[1].value.trim()
                                });
                            }
                        });
                        
                        if (prices.length > 0) {
                            upgrade_templates[nameInput.value.trim()] = prices;
                        }
                    }
                });
                
                const basicDataToSave = {
                    airports,
                    meals,
                    upgrade_templates
                };
                
                const response = await fetch('/api/basic_data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(basicDataToSave)
                });
                
                if (response.ok) {
                    if (showAlert) {
                        alert('基础数据保存成功！');
                    }
                    return true;
                } else {
                    if (showAlert) {
                        alert('基础数据保存失败！');
                    }
                    return false;
                }
            } catch (error) {
                console.error('基础数据保存失败:', error);
                if (showAlert) {
                    alert('基础数据保存失败！');
                }
                return false;
            }
        }
    </script>
</body>
</html>